package net.xiaosaguo.mymall.product.exception;

import lombok.extern.slf4j.Slf4j;
import net.xiaosaguo.common.exception.BizCodeEnum;
import net.xiaosaguo.common.utils.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * description: 全局异常统一处理
 *
 * @author xiaosaguo
 * @date 2020/06/10
 */
@Slf4j
@RestControllerAdvice(basePackages = "net.xiaosaguo.mymall.product.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        /// log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        Map<String, String> errorFieldMap = new HashMap<>(e.getBindingResult().getFieldErrors().size());
        e.getBindingResult().getFieldErrors().forEach(errorField ->
                errorFieldMap.put(errorField.getField(), errorField.getDefaultMessage()));
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage())
                .put("data", errorFieldMap);
    }

    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误：", throwable);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
